<template>
    <div class="export-panel">
        <button class="btn-export" @click="exportImage('png')">导出PNG图片</button>
        <button class="btn-export" @click="exportImage('jpg')">导出JPG图片</button>
        <button class="btn-export" @click="exportExcel">导出Excel表格</button>
    </div>
</template>

<script setup>
import html2canvas from 'html2canvas'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
import { ref, nextTick } from 'vue'

const props = defineProps({
    policies: {
        type: Array,
        default: () => []
    },
    exportAreaSelector: {
        type: String,
        default: '#timelineContainer'
    }
})

const exporting = ref(false)

async function exportImage(type = 'png') {
    if (exporting.value) return
    exporting.value = true

    try {
        const source = document.querySelector(props.exportAreaSelector)
        if (!source) {
            alert('未找到导出区域元素，请检查选择器！')
            exporting.value = false
            return
        }

        await document.fonts.ready
        await nextTick()

        // 先找到实际内容容器，比如你的.timeline-items，因为它决定了宽度和高度
        const content = source.querySelector('.timeline-items') || source

        // 计算内容真实宽高
        const contentWidth = content.scrollWidth+100
        const style = getComputedStyle(content)
        const heightWithoutTransform = content.scrollHeight
        const verticalOffset = 80 * 2  // policy-card上下移动的translateY距离，需要与样式保持同步

        const contentHeight = heightWithoutTransform + verticalOffset

        // 克隆节点
        const clone = source.cloneNode(true)

        // 清除滚动与限制，设置宽高覆盖所有内容
        clone.style.position = 'absolute'
        clone.style.top = '0'
        clone.style.left = '0'
        clone.style.width = contentWidth + 'px'
        clone.style.height = contentHeight + 'px'
        clone.style.overflow = 'visible'
        clone.style.maxWidth = 'none'
        clone.style.maxHeight = 'none'
        clone.style.transform = 'none'
        clone.style.zIndex = '-10000'  // 放最下面，不影响页面

        // 包裹容器
        const wrapper = document.createElement('div')
        wrapper.style.position = 'fixed'
        wrapper.style.top = '-9999px'
        wrapper.style.left = '0'
        wrapper.style.zIndex = '-10000'
        wrapper.style.overflow = 'visible'
        wrapper.appendChild(clone)
        document.body.appendChild(wrapper)

        // 传入明确的宽高确保截图完整
        const canvas = await html2canvas(clone, {
            backgroundColor: '#ffffff',
            scale: 2,
            useCORS: true,
            allowTaint: false,
            width: contentWidth,
            height: contentHeight,
            scrollX: -window.scrollX,
            scrollY: -window.scrollY,
            windowWidth: document.documentElement.clientWidth,
            windowHeight: document.documentElement.clientHeight,
        })

        document.body.removeChild(wrapper)

        const mimeType = type === 'jpg' ? 'image/jpeg' : 'image/png'
        const fileExt = type === 'jpg' ? 'jpg' : 'png'

        canvas.toBlob(blob => {
            if (!blob) {
                alert('图片生成失败！')
                exporting.value = false
                return
            }
            saveAs(blob, `政策时间轴导出_${new Date().toISOString().slice(0, 10)}.${fileExt}`)
            exporting.value = false
        }, mimeType)
    } catch (error) {
        alert('导出图片出错: ' + error.message)
        exporting.value = false
    }
}

function exportExcel() {
    if (exporting.value) return
    exporting.value = true

    try {
        const data = props.policies.map(p => ({
            标题: p.title || '',
            时间: p.date || '',
            级别: p.level || '',
            相关度: p.relevance != null ? p.relevance : '',
            描述: p.description || ''
        }))

        const ws = XLSX.utils.json_to_sheet(data)
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, '政策数据')

        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
        const blob = new Blob([wbout], { type: 'application/octet-stream' })

        saveAs(blob, `政策数据导出_${new Date().toISOString().slice(0, 10)}.xlsx`)
    } catch (error) {
        alert('导出Excel失败: ' + error.message)
    } finally {
        exporting.value = false
    }
}
</script>

<style scoped>
.export-panel {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    padding: 12px 16px;
    background: var(--color-surface, #f9f9f9);
    border-radius: 8px;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
    user-select: none;
    color: var(--color-textPrimary, #333);
}

.btn-export {
    flex: none;
    padding: 8px 16px;
    background: var(--color-accent, #007bff);
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-weight: 600;
    transition: background 0.3s;
    user-select: none;
}

.btn-export:hover {
    background: var(--color-accentHover, #0056b3);
}

.btn-export:disabled {
    background: var(--color-border, #ccc);
    cursor: not-allowed;
    color: var(--color-textSecondary, #888);
}
</style>
